package com.cq.smartelebicycle.fragment;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.cq.smartelebicycle.R;
import com.cq.smartelebicycle.view.BluetoothListAdapter;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

public class BluetoothFragment extends Fragment{
	
	public static final String TAG_ID = "BluetoothFragment";
	
	private View rootView;
	private TextView bluetooth_state;
	private List<BluetoothDevice> list;
	private ListView bluetoothDeviceList;
    private Context context;
    private BluetoothListAdapter adapter;
    private BluetoothAdapter mBluetoothAdapter;
    public static BluetoothSocket mBluetoothSocket; 
    
    private static final String BLUETOOTH_UUID = "00111101-0000-1000-8001-B0805F9B34FB";
    
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		rootView = inflater.inflate(R.layout.bluetooth_fragment, container, false);

		
		return rootView;//super.onCreateView(inflater, container, savedInstanceState);
	}
	
	
	

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		context = getActivity();
		
        IntentFilter intent = new IntentFilter();  
        intent.addAction(BluetoothDevice.ACTION_FOUND);// 用BroadcastReceiver来取得搜索结果  
        intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);  
        intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);  
        intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);   
		context.registerReceiver(mReceiver, intent);
		 mBluetoothAdapter= BluetoothAdapter.getDefaultAdapter();
		list = new ArrayList();
		bluetooth_state =(TextView)rootView.findViewById(R.id.bluetooth_state);
		bluetooth_state.setText("点击搜索蓝牙设备");
		bluetooth_state.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				list.clear();
				openBluetoothDevice();
				
			}
			
		});
		
		
		bluetoothDeviceList =(ListView)rootView.findViewById(R.id.bluetooth_list);
		adapter = new BluetoothListAdapter(this,list);
		bluetoothDeviceList.setAdapter(adapter);
	
	}

	
	private void openBluetoothDevice(){
		bluetooth_state.setText("正在搜索中...");

	     if(!mBluetoothAdapter.isEnabled()){
	    	 mBluetoothAdapter.enable();
	     }
	     
	     if(mBluetoothAdapter.isDiscovering()){
	    	 mBluetoothAdapter.cancelDiscovery();
	     }
	     mBluetoothAdapter.startDiscovery();
	     
	}
	
	
	BroadcastReceiver mReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context arg0, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction(); 
			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
				BluetoothDevice device = intent
						.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);		
				list.add(device);
				UpdateBluetoothDevice();
				if(device.getBondState() == BluetoothDevice.BOND_BONDED){
					connect(device);
				}
				
				
			}else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED
					.equals(action)){
				bluetooth_state.setText("搜索完成");
				UpdateBluetoothDevice();
			}else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
				 Log.d("SIMMON","onReceive 5"); 
				UpdateBluetoothDevice();
				
			}
		}
		
	};
	
	
	private void UpdateBluetoothDevice(){
		 adapter.notifyDataSetChanged();

	}
	
	public void connect(BluetoothDevice btDev){
		UUID uuid = UUID.fromString(BLUETOOTH_UUID);  
        try {  
        	mBluetoothSocket = btDev.createRfcommSocketToServiceRecord(uuid);  
            mBluetoothSocket.connect();  
            UpdateBluetoothDevice();
        } catch (IOException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
	}
	
	public void cancelconnect(BluetoothDevice btDev){
		UUID uuid = UUID.fromString(BLUETOOTH_UUID);  
        try {  
        	mBluetoothSocket = btDev.createRfcommSocketToServiceRecord(uuid);  
            mBluetoothSocket.close();  
            UpdateBluetoothDevice();
        } catch (IOException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
	}




	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		super.onDestroyView();
		context.unregisterReceiver(mReceiver);
	}
	
	
	
	 

}
